<template>
    <!-- 整体容器 -->
    <div class="pages">
        <el-container class="page-container">
            <!-- 搜索 -->
            <el-header class="page-header">
                <el-space :size="10">
                    <el-select v-model="lookupData.status" placeholder="请选择用户状态">
                        <el-option v-for="(item,index) in options.optionStatus" :key="index" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-select v-model="lookupData.level" placeholder="请选择用户会员等级">
                        <el-option v-for="(item,index) in options.optionLevel" :key="index" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-select v-model="lookupData.gender" placeholder="请选择用户性别">
                        <el-option v-for="(item,index) in options.optionSex" :key="index" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-input v-model.trim="lookupData.id" placeholder="请输入用户ID" clearable />
                    <el-input v-model.trim="lookupData.nickname" placeholder="请输入昵称" clearable />
                    <el-button type="primary" :icon="Search" @click="handlerFind">查找</el-button>
                </el-space>
            </el-header>
            <el-main class="page-main">
                <!-- 表格 -->
                <div class="main-table">
                    <el-table style="width: 100%" :data="tableData" border>
                        <el-table-column prop="id" label="用户ID" align="center" sortable/>
                        <el-table-column prop="nickname" label="昵称" align="center" />
                        <el-table-column prop="phone" label="手机号码" align="center" />
                        <el-table-column label="性别" align="center">
                            <template #default="scope">
                                <el-tag>{{scope.row.gender==2?'男':'女'}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="会员等级" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.level==0?'info':'warning'">
                                    {{scope.row.level==0?'普通会员':'VIP会员'}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="生日" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.birthday">
                                    {{new Date(scope.row.birthday).friendlyTime(1).split(' ')[0]}}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.status!=0?'':'danger'">{{scope.row.status==0?'冻结':'激活'}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="上次登录时间" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.gmtLastLogin">
                                    {{new Date(scope.row.gmtLastLogin).friendlyTime(2)}}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="lastLoginIp" label="上次登录IP" align="center" />
                        <el-table-column label="操作" align="center" width="160px">
                            <template #default="scope">
                                <el-button :type="scope.row.status==0?'primary':'danger'" @click="handlerFrozen(scope.row)">{{scope.row.status==0?'激活':'冻结'}}</el-button>
                                <el-button type="primary" @click="handlerEdit(scope.row)">编辑</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页组件 -->
                <div class="page-pagination">
                    <Pagination v-bind="vipUserPagination" @handle-pagination="emitEntProps"/>
                </div>
                <!-- 回到顶部组件 -->
                <el-backtop :right="100" :bottom="100" target=".el-main" ref="refBacktop" />
                <!-- 表单对话框 -->
                <el-dialog v-model="dialogFormVisible" title="编辑" width="40%">
                    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
                        <el-form-item label="用户昵称" prop="nickname" class="is-required">
                            <el-input v-model="ruleForm.nickname" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="用户手机号" prop="phone" class="is-required">
                            <el-input v-model="ruleForm.phone" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="用户性别" prop="gender" class="is-required">
                            <el-select v-model="ruleForm.gender">
                                <el-option
                                    v-for="(item,index) in options.optionSex.slice(0,options.optionStatus.length-1)"
                                    :key="index" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="用户等级" prop="level" class="is-required">
                            <el-select v-model="ruleForm.level">
                                <el-option
                                    v-for="(item,index) in options.optionLevel.slice(0,options.optionStatus.length-1)"
                                    :key="index" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="用户状态" prop="status" class="is-required">
                            <el-select v-model="ruleForm.status">
                                <el-option
                                    v-for="(item,index) in options.optionStatus.slice(0,options.optionStatus.length-1)"
                                    :key="index" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ClassPagination } from '#/index';
import { reactive, ref, nextTick } from "vue";
import { Search } from '@element-plus/icons-vue';
import { post } from "@/utils/index";
import { ElMessage } from "element-plus";
import type { FormInstance } from 'element-plus'


const ruleFormRef = ref<FormInstance>()
/**
 * 表格数据
 */
const tableData: TypeVipUser[] = reactive([])
/**
 * 回到顶部组件的实例
 */
const refBacktop = ref()
/**
 * 分页数据
 */
const vipUserPagination = reactive(new ClassPagination())
/**
 * 表单对话框默认隐藏,true为显示,false为隐藏
 */
const dialogFormVisible = ref<boolean>(false)
/**
 * 查找的数据
 */
const lookupData: TypeVipUserForm = reactive({
    id: '',
    nickname: '',
    level: undefined,
    gender: undefined,
    status: undefined,
})
/**
 * 表单对话框数据
 */
 const ruleForm: TypeVipUserForm = reactive({
    nickname: '',   //用户昵称
    phone: '',      //用户电话号码
    gender: '',      //用户性别
    status: '',      //用户状态
    level: '',        //用户等级
    id: ''
})
/**
 * 下拉列表数据
 */
 const options: TypeVipUserOptions = reactive({
    optionStatus: [{ value: '0', label: '冻结', },{ value: '1', label: '激活', },{ value: '', label: '全部', }],
    optionLevel: [{ value: '0', label: '普通会员', },{ value: '1', label: 'VIP会员', },{ value: '', label: '全部', }],
    optionSex: [{ value: '2', label: '男', },{ value: '1', label: '女', },{ value: '', label: '全部', }]
})



/**
 * 手机号验证
 * @param rule 规则
 * @param value 输入框的值
 * @param callback 回调
 */
function validatePhone(rule: Object, value: string, callback: Function) {
    let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;//11位手机号码正则
    if (!reg_tel.test(value)) {
        callback(new Error("请正确填写您的手机号码！"))
    } else {
        callback()
    }
}
/**
 * 表单验证规则
 */
const rules = reactive({
    nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' },{ validator: validatePhone, trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: ['blur', 'change'] },],
    level: [{ required: true, message: '请选择等级', trigger: ['blur', 'change'] },],
    status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] },],
})
/**
 * 表单对话框确认按钮
 * @param formEl 
 */
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let data = {
                _gp: 'admin.user',
                _mt: 'edit',
                user: JSON.stringify({ ...ruleForm })
            }
            post(data).then((res) => {
                console.log(res);
                if (200 === res.errno) {
                    getInitVipUser()
                    dialogFormVisible.value = false
                    ElMessage.success("修改成功")
                } else {
                    ElMessage.error(res.errmsg)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}
/**
 * 请求的表格数据
 */
function getInitVipUser() {
    let data = {
        _gp: 'admin.user',
        _mt: 'list',
        id: lookupData.id,  //用户ID
        nickname: lookupData.nickname,  //用户昵称
        level: lookupData.level,    //数量
        gender: lookupData.gender,  //用户性别
        status: lookupData.status,  //用户类型
        pageNo: vipUserPagination.page, //页数
        limit: vipUserPagination.limit  //每页几条
    }
    post(data).then(res => {
        console.log(res);
        if (200 === res.errno) {
            let { items, total } = res.data
            tableData.length = 0    //清零
            tableData.push(...items)
            vipUserPagination.total = total
        } else {
            tableData.length = 0    //清零
            ElMessage.error(res.errmsg)
        }
    })
}
/**
 * 查找按钮
 */
function handlerFind() {
    console.log("查找按钮");
    vipUserPagination.page = 1
    getInitVipUser()
}
/**
 * 冻结
 */
function handlerFrozen(row: TypeVipUser) {
    console.log("冻结");
    let data = {
        _gp: 'admin.user',
        _mt: 'editStatus',
        userId: row.id,
        status: row.status ? '0' : '1'
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            getInitVipUser()
            ElMessage.success("操作成功")
        } else {
            ElMessage.success(res.errmsg)
        }
    })
}
/**
 * 用户编辑
 */
function handlerEdit(row: TypeVipUser) {
    dialogFormVisible.value = true
    ruleForm.gender = row.gender+''
    ruleForm.level = row.level+''
    ruleForm.nickname = row.nickname
    ruleForm.phone = row.phone
    ruleForm.status = row.status+''
    ruleForm.id = row.id+''
}
/**
 * 分页组件传递过来的数据
 * @param val
 * page:页数
 * limit:条数
 */
 function emitEntProps(val: { page: number, limit: number }) {
    let paging = vipUserPagination
    paging.page = val.page
    paging.limit = val.limit
    getInitVipUser()
}

// 初始请求
getInitVipUser()
</script>

<style lang="less" scoped>
/deep/.el-form-item__content:first-child {
    justify-content: right;
}
// 表单对话框样式
.el-form {
    padding: 0px 20px;
    /deep/.el-form-item--default .el-form-item__label {
        width: 100px;
        justify-content: left;
    }
}
</style>